import { ApiLogin, ApiLogOut, ApiGetInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {defineStore} from "pinia";
import cache from '@/plugins/cache'
import useCartStore from "@/store/modules/cart.js";

const UserInfoKey = 'Coupon-UserInfo'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      userInfo: cache.local.getJSON(UserInfoKey) || {},
    }),
    getters: {
      isLogin: state => !!state.token,
    },

    actions: {
      // 登录
      login(userInfo) {
        return new Promise((resolve, reject) => {
          ApiLogin(userInfo).then(async res => {
            setToken(res.data.token)
            this.token = res.data.token
            await this.getInfo()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          ApiGetInfo().then(res => {
            this.userInfo = res.data
            cache.local.setJSON(UserInfoKey, res.data)
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          ApiLogOut().then(() => {
            this.token = ''
            this.userInfo = {}
            removeToken()
            // 删除指定的键
            sessionStorage.removeItem('isAuthorized');
            cache.local.remove(UserInfoKey)
            useCartStore().clearCartList()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 前端登出
      FedLogOut() {
        return new Promise(resolve => {
          this.token = ''
          this.userInfo = {}
          removeToken()
          cache.local.remove(UserInfoKey)
          useCartStore().clearCartList()
          resolve()
        })
      }
    }
  })

export default useUserStore
